const {objectValueAllEmpty} = require('../utils')
const {WhiteboardsModel} = require('../db');

// ws在路由中不好使，直接在app中使用
module.exports = function (app) {
  var connections = {}; // 存放连接的地方
  app.ws('/whiteboard/connect', function (ws, req) {
    if (!(req.query && req.query.whiteboard_id) || objectValueAllEmpty(req.query)) {
      return
    }
    const {whiteboard_id, user_id} = req.query;
    // 记录连接
    addConn(connections, ws, whiteboard_id, user_id);

    WhiteboardsModel.findOne({
      _id: whiteboard_id
    }, function (err, result) {
      // 开启连接返回的消息
      ws.send(`${JSON.stringify({errno: 0, message: 'ok', data: result})}`);
    })

    // 收到message进行广播
    ws.on("message", function (msg) {
      let params = JSON.parse(msg)
      if(params.user_id==='guest') return
      broadcast(connections, msg, ws);

      // 保存画布内容
      if (!objectValueAllEmpty(params) && params.content) {
        WhiteboardsModel.updateOne({_id: params.whiteboard_id}, {content: params.content,lastUpdatedTime:Date.now()},function (err) {
          // ，，，
        })
      }
    });

    // 连接关闭，connections中的连接
    ws.on('close', function (e) {
      delWsFromConn(connections, user_id, whiteboard_id);
    })
  })

  /**
   * 新增白板
   */
  app.get('/whiteboard/add', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }
    const {user_id, name} = req.query;
    console.log(name)
    if(!name){
      res.send({
        errno: 202,
        message:"白板名未定义"
      })
      return;
    }

    WhiteboardsModel.create({
      name:name+'',
      creatorId: user_id,
      creationTime: Date.now(),
      lastUpdatedTime: Date.now(),
      readOnly: 0,
      content: []
    }, function (err, newWhiteboard) {
      if (!err) {
        res.send({
          errno: 0,
          newWhiteboard
        })
      } else {
        res.send({
          errno: 201,
          message: err.message
        })
      }
    })
  })

  /**
   * 删除白板
   */
  app.get('/whiteboard/delete', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }
    const {whiteboard_id, user_id} = req.query;

    WhiteboardsModel.deleteOne({_id: whiteboard_id, creatorId: user_id},
        function (err, {deletedCount}) {
          if (err) {
            res.send({
              errno: 201,
              message: err.message
            })
          } else {
            if (deletedCount && deletedCount === 0) {
              // 删除数为0
              res.send({
                errno: 202,
                message: '删除失败，白板id或者用户id错误'
              })
            } else {
              res.send({
                errno: 0,
                message: 'deleteSuccess'
              })
            }
          }
        }
    )
  })

  /**
   * 修改白板readOnly
   */
  app.get('/whiteboard/update/readOnly', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }

    const {whiteboard_id, user_id, readOnly} = req.query;
    WhiteboardsModel.updateOne({_id: whiteboard_id, creatorId: user_id}, {readOnly},
        function (err, {matchedCount}) {
          if (err) {
            res.send({
              errno: 201,
              message: err.message
            })
          } else if (matchedCount === 0) {
            res.send({
              errno: 202,
              message: '参数值错误'
            })
          } else {
            res.send({
              errno: 0,
              message: 'success'
            })
          }
        }
    )
  })

  /**
   * 修改白板name
   */
  app.get('/whiteboard/update/name', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }

    const {whiteboard_id, user_id, name} = req.query;
    WhiteboardsModel.updateOne({_id: whiteboard_id, creatorId: user_id}, {name},
        function (err, {matchedCount}) {
          if (err) {
            res.send({
              errno: 201,
              message: err.message
            })
          } else if (matchedCount === 0) {
            res.send({
              errno: 202,
              message: '参数值错误'
            })
          } else {
            res.send({
              errno: 0,
              message: 'success'
            })
          }
        }
    )
  })

  /**
   * 根据白板id获取白板
   */
  app.get('/whiteboard/get', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }

    const {whiteboard_id} = req.query;
    WhiteboardsModel.findOne({_id: whiteboard_id}, function (err, whiteboard) {
      if (err) {
        res.send({
          errno: 201,
          message: err.message
        })
      } else {
        res.send({
          errno: 0,
          message: 'success',
          data: {whiteboard}
        })
      }
    });
  })

  /**
   * 查询用户创建的白板
   */
  app.get('/whiteboard/info', function (req, res) {
    if (objectValueAllEmpty(req.query)) {
      res.send({
        errno: 202,
        message: '参数错误'
      })
      return
    }

    const {pageNo, limit = 10, user_id} = req.query;
    let skip = (pageNo - 1) * limit; // 分页跳过条数
    const query = WhiteboardsModel.find({creatorId: user_id}).limit(limit).skip(skip);
    query.exec(function (err, whiteboards) {
      if (err) {
        res.send({
          errno: 201,
          message: err
        })
      } else {
        WhiteboardsModel.countDocuments({creatorId: user_id}, function (err2, count) {
          res.send({
            errno: 0,
            message: 'success',
            data: {whiteboards, total: count}
          })
        })
      }
    });
  })

}

/**
 * 为不同白板记录连接
 * 参数: 存放的对象，连接，白板id(用于当属性名),user_id标识ws
 * 形如：
 * { '白板id':[ws1,ws2...] }
 */
function addConn(conn, ws, key, user_id) {
  if (!(key in conn)) {
    conn[key] = [];
  }
  ws.user_id = user_id
  conn[key].push(ws);
}

/**
 * 从conn中删除ws
 */
function delWsFromConn(conn, user_id, whiteboard_id) {
  if (whiteboard_id in conn) {
    let index = conn[whiteboard_id].findIndex(item => user_id === item.user_id)
    conn[whiteboard_id].splice(index, 1);

    // 该白板下的websocket连接被清空
    if (conn[whiteboard_id].length < 1) {
      delete conn[whiteboard_id];
    }
  }
}

/**
 * 广播
 */
function broadcast(conn, msg, unlessWs) {
  if (objectValueAllEmpty(conn)) return;
  let params = JSON.parse(msg);

  // 校验参数
  if (objectValueAllEmpty(params)) {
    unlessWs.send('参数错误')
    return
  }

  // 进行广播
  conn[params.whiteboard_id].forEach(ws => {
    ws.send(msg)
  })
}